package web

import (
	"encoding/json"
	"errors"
	"net/http"
	"strings"

	projCom "ZHONGYIHANGYAN/commUtils/projComm"
	"ZHONGYIHANGYAN/web/middlewares"

	"github.com/gin-gonic/gin"
)

type WebReply struct {
	Status  int         `json:"status"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

type WebInParmId struct {
	Id string `json:"id"`
}

type WebInParmUserId struct {
	Id string `json:"userId"`
}

type CheckToken func(*gin.Context)

var (
	ErrWeb_GetParaFailed   = errors.New("get Para failed")
	ErrWeb_ParseJsonFailed = errors.New("parse json failed")
)

type WebRouter struct {
	f func(c *gin.Context, replayData *interface{}) error
}

func (r *WebRouter) Func(c *gin.Context) {
	rep := WebReply{}

	defer func() {
		if rep.Message == "" {
			rep.Status = 2
			rep.Message = "接口出现异常"
		}
		c.JSON(200, rep)
	}()

	if err := r.f(c, &rep.Data); err != nil {
		if strings.Contains(err.Error(), projCom.ErrAll.Error()) {
			rep.Status = 2
			comma := strings.Index(err.Error(), ":")
			comma += 1 //去除冒号
			strErr := err.Error()[comma:]
			rep.Message = strErr
		} else if strings.Contains(err.Error(), projCom.ErrPart.Error()) {
			rep.Status = 1
			comma := strings.Index(err.Error(), ":")
			comma += 1 //去除冒号
			strErr := err.Error()[comma:]
			rep.Message = strErr
		} else {
			rep.Status = 2
			rep.Message = err.Error()
		}

		return
	}

	rep.Status = 0
	rep.Message = "成功"
}
func NewWebRouter(f func(c *gin.Context, replayData *interface{}) error) *WebRouter {
	web := new(WebRouter)
	web.f = f

	return web
}

type Web struct {
	e                 *gin.Engine
	regRoutersHandles []func(*gin.RouterGroup)
}

func (w *Web) GetPayload(c *gin.Context, out interface{}) error {
	data, err := c.GetRawData()
	if err != nil {
		return ErrWeb_GetParaFailed
	}
	if len(data) == 0 {
		return nil
	}
	if err = json.Unmarshal(data, out); err != nil {
		return err
		// return ErrWeb_ParseJsonFailed
	}

	return nil
}
func (w *Web) RegRouters(handle ...func(*gin.RouterGroup)) {
	w.regRoutersHandles = append(w.regRoutersHandles, handle...)
}
func (w *Web) RegLogin(login gin.HandlerFunc) {
	w.e.POST("/login", login)
}
func (w *Web) RegLogout(logout gin.HandlerFunc) {
	w.e.GET("/logout", logout)
}
func (w *Web) RegVersion(version gin.HandlerFunc) {
	w.e.GET("/version", version)
}
func (w *Web) RegSystemDefaultData(data gin.HandlerFunc) {
	w.e.GET("/systemDefaultData", data)
}
func (w *Web) Start(url string) {
	gApi := w.e.Group("/api")

	{
		for _, handle := range w.regRoutersHandles {
			handle(gApi)
		}
	}

	// 设置静态文件路径
	// w.e.StaticFS("/record", http.Dir("/home/record/File"))
	w.e.StaticFS("/record", http.Dir("./record"))

	// 重定向首页
	w.e.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusFound, "/static/index.html")
	})
	w.e.Run(url)
}
func New() *Web {
	// 关闭Denug模式，生产环境下设置为Release模式
	gin.SetMode(gin.ReleaseMode)

	w := new(Web)

	e := gin.Default()
	e.Use(middlewares.Cors())
	w.e = e

	return w
}
